﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Fsb.Utility;
using VideoCache.Aggregation.Interfaces;

namespace VideoCache.Aggregation.Implements
{
    [Site("youku.com")]
    class YoukuFetcher : IFetcher
    {
        public VideoModel GetToken(string url)
        {
            return this.GetTokenByUrl(url);
        }

        private string GetTokenByShareUrl(string url)
        {
            // static.youku.com/v1.0.0318/v/swf/loader.swf?VideoIDS=XNTQ0MDM5NTY4&ShowId=0&category=91&Cp=0&Light=on&THX=off&unCookie=0&frame=0&pvid=1366178240168LlM&Tid=0&isAutoPlay=true&Version=/v1.0.0850&show_ce=0&winType=interior&Type=Folder&Fid=19176456&Pt=0&Ob=1&plchid=a&embedid=AjEzNjAwOTg5MgJ3d3cueW91a3UuY29tAi8=&vext=bc%3D%26pid%3D%26unCookie%3D0%26frame%3D0%26type%3D1%26fob%3D1%26fpo%3D0%26svt%3D0%26emb%3DAjEzNjAwOTg5MgJ3d3cueW91a3UuY29tAi8%3D%26dn%3D%E7%BD%91%E9%A1%B5%26hwc%3D1%26mtype%3Doth

            return UrlHelper.GetParameter(url, "VideoIDS");
        }

        private VideoModel GetTokenByUrl(string url)
        {
            // v.youku.com/v_show/id_XNTQzOTEyNzMy.html

            string html = HttpUtility.Get(url, Encoding.UTF8);

            string token = StringUtility.SubString(html, "var videoId2= '", "'");

            if (!string.IsNullOrEmpty(token))
            {
                // http://v.youku.com/player/getPlayList/VideoIDS/XNDg1NTk4NzY4

                string json = HttpUtility.Get(string.Format("http://v.youku.com/player/getPlayList/VideoIDS/{0}", token), Encoding.UTF8);
                Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
                if (jObject != null)
                {
                    Newtonsoft.Json.Linq.JArray jArray = jObject["data"] as Newtonsoft.Json.Linq.JArray;
                    return new VideoModel(token, jArray[0]["title"].ToString().Trim('\"'));
                }
            }

            return null;
        }
    }
}